<!-- ERC-备件管理-备件入库页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="入库地块">
              <px-select v-model="queryParams.facCode" placeholder="请选择入库地块" filterable clearable>
                <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="入库单号">
              <px-input
                v-model="queryParams.inNum"
                placeholder="请输入入库单号"
                autocomplete="off"
                maxlength="50"
                clearable
                @blur="queryParams.inNum = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="入库主题">
              <px-input
                v-model="queryParams.inName"
                placeholder="请输入入库主题"
                autocomplete="off"
                maxlength="50"
                clearable
                @blur="queryParams.inName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="入库日期" prop="inDate">
              <px-date-picker
                v-model="queryParams.inDate"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="审核状态" prop="approvalStatus">
              <px-select v-model="queryParams.approvalStatus" placeholder="请选择审核状态" filterable clearable>
                <px-option v-for="item in approvalStatusList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div v-has="'ERC_SPAREPARTS_WAREHOUSING_ADD'" class="equip-table-btn">
        <px-dropdown trigger="click" @command="addSpareParts">
          <px-button type="primary"
            >新增入库单
            <px-icon style="margin-left: 4px"><ArrowDown /></px-icon>
          </px-button>
          <template #dropdown>
            <px-dropdown-menu>
              <px-dropdown-item v-for="item in sourceList" :key="item.value" :command="item.value">{{ item.name }}</px-dropdown-item>
            </px-dropdown-menu>
          </template>
        </px-dropdown>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 346px)" border>
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button v-if="item.num && showRowText('ERC_SPAREPARTS_WAREHOUSING_VIEW')" link type="primary" @click="handleView(scope.row)">
              {{ scope.row.inNum }}
            </px-button>
            <span v-else-if="item.num && !showRowText('ERC_SPAREPARTS_WAREHOUSING_VIEW')">{{ scope.row.inNum }}</span>
            <px-tooltip v-else-if="item.approvalStatus" content="点击查看历史进度" placement="top">
              <span style="cursor: pointer" @click="handleProcess(scope.row)">
                <px-tag
                  v-if="scope.row.approvalStatus"
                  effect="plain"
                  :style="{
                    color: `${tagColorList[scope.row.approvalStatus]}`,
                    border: `1px solid ${tagBorderColorList[scope.row.approvalStatus]}`,
                    backgroundColor: `${tagBgColorList[scope.row.approvalStatus]}`
                  }"
                >
                  {{ scope.row.approvalStatusDesc }}
                </px-tag>
                <span v-else> {{ scope.row.approvalStatusDesc || "-" }} </span>
              </span>
            </px-tooltip>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_SPAREPARTS_WAREHOUSING_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <!-- 已驳回状态+是创建人才能编辑 -->
            <px-tooltip v-if="scope.row.approvalStatus === 'reject' && userId === scope.row.createBy" content="编辑" placement="top">
              <px-button v-has="'ERC_SPAREPARTS_WAREHOUSING_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <!-- 审核中状态+是审核人才能审核 -->
            <px-tooltip v-if="scope.row.approvalStatus === 'approving' && userId === scope.row.approverId" content="审核" placement="top">
              <px-button v-has="'ERC_SPAREPARTS_WAREHOUSING_CHECK'" link type="primary" @click="handleCheck(scope.row)">
                <component :is="markRaw(stamp)" />
              </px-button>
            </px-tooltip>
            <!-- 审核中状态+是入库人才能转审 -->
            <px-tooltip v-if="scope.row.approvalStatus === 'approving' && userId === scope.row.inOperateId" content="转审" placement="top">
              <px-button v-has="'ERC_SPAREPARTS_WAREHOUSING_TOCHECK'" link type="primary" @click="handleToCheck(scope.row)">
                <component :is="markRaw(transfer)" />
              </px-button>
            </px-tooltip>
            <!-- <px-tooltip content="删除" placement="top">
              <px-button v-has="'ERC_SPAREPARTS_WAREHOUSING_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip> -->
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :addType="addType"
      :drawerType="drawerType"
      :sparePartsId="sparePartsId"
      :userId="userId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :drawerType="drawerType"
      :sparePartsId="sparePartsId"
      :userId="userId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 审核弹窗 -->
    <CheckDialog
      :dialogVisible="checkVisible"
      :busId="sparePartsId"
      :approverId="approverId"
      :approverName="approverName"
      type="wareHousing"
      @closeDialog="
        checkVisible = false;
        queryTable();
      "
    />
    <!-- 转审弹窗 -->
    <ToCheckDialog
      :dialogVisible="toCheckVisible"
      :busId="sparePartsId"
      :approverId="approverId"
      :approverName="approverName"
      type="wareHousing"
      @closeDialog="
        toCheckVisible = false;
        queryTable();
      "
    />
    <!-- 进度弹窗 -->
    <ProcessDialog :dialogVisible="processVisible" :sparePartsId="sparePartsId" type="wareHousing" @closeDialog="processVisible = false" />
  </div>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/erc/common";
import { deleteSparePartsWarehousing, querySparePartsWarehousing, sourceSparePartsWarehousing } from "@/api/erc/spareParts";
import stamp from "@/assets/svg/operation/stamp.svg?component";
import transfer from "@/assets/svg/operation/transfer.svg?component";
import { PxMessage, PxMessageBox } from "px-ui";
import { showRowText } from "@/utils/pengxi";
import { markRaw, onMounted, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import CheckDialog from "../components/CheckDialog.vue";
import ProcessDialog from "../components/ProcessDialog.vue";
import ToCheckDialog from "../components/ToCheckDialog.vue";
import AddSparePartsDetail from "./components/AddSparePartsDetail.vue";
import ViewSparePartsDetail from "./components/ViewSparePartsDetail.vue";

const route = useRoute();
const router = useRouter();
const approvalStatusList = [
  { id: 0, name: "审批通过", value: "pass" },
  { id: 1, name: "审批中", value: "approving" },
  { id: 2, name: "驳回修改", value: "reject" },
  { id: 3, name: "驳回不通过", value: "not_pass" }
];
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  facCodeList: [],
  sourceList: [],
  addType: "buy",
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    facCode: "",
    inNum: "",
    inName: "",
    startTime: "",
    endTime: "",
    approvalStatus: ""
  },
  tableColumns: [
    { prop: "inNum", label: "入库单号", minWidth: "160", showOverflowTooltip: true, num: true, fixed: "left" },
    { prop: "sourceDesc", label: "入库类型", minWidth: "150", showOverflowTooltip: true },
    { prop: "inName", label: "入库主题", minWidth: "150", showOverflowTooltip: true },
    { prop: "inDate", label: "入库时间", minWidth: "140", showOverflowTooltip: true },
    { prop: "createName", label: "操作人", minWidth: "120", showOverflowTooltip: true },
    { prop: "approverName", label: "审核人", minWidth: "120", showOverflowTooltip: true },
    { prop: "approvalStatus", label: "审核状态", minWidth: "120", showOverflowTooltip: true, approvalStatus: true }
  ],
  tableData: [],
  total: 0,
  userId: "",
  drawerType: "add",
  sparePartsId: "",
  approverId: "",
  approverName: "",
  toCheckVisible: false,
  checkVisible: false,
  processVisible: false
});
const {
  isMain,
  isView,
  facCodeList,
  sourceList,
  addType,
  queryParams,
  tableColumns,
  tableData,
  total,
  userId,
  drawerType,
  sparePartsId,
  approverId,
  approverName,
  toCheckVisible,
  checkVisible,
  processVisible
} = toRefs(state);

const tagColorList = {
  pass: "#10B981",
  approving: "#F59E0B",
  reject: "#EF4444",
  not_pass: "#9254DE"
};

const tagBorderColorList = {
  pass: "#B7EAD9",
  approving: "#FCE2B6",
  reject: "#FAC7C7",
  not_pass: "#DDC2FF"
};

const tagBgColorList = {
  pass: "#E8F8F3",
  approving: "#FEF5E6",
  reject: "#FEECEC",
  not_pass: "#F2E7FF"
};

// 进入页面时触发
onMounted(() => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  if (route?.query && route?.query?.id) {
    sparePartsId.value = +route?.query?.id;
    isMain.value = false;
    isView.value = true;
  } else {
    isMain.value = true;
    isView.value = true;
    querySelectList();
    queryTable();
  }
});
// 获取下拉框
const querySelectList = async () => {
  sourceList.value = await sourceSparePartsWarehousing({});
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
};
// 获取开始日期及结束日期
const changeDate = val => {
  if (val && val.length > 0) {
    queryParams.value.startTime = val[0] + " 00:00:00";
    queryParams.value.endTime = val[1] + " 23:59:59";
  } else {
    queryParams.value.startTime = "";
    queryParams.value.endTime = "";
  }
};
// 查询备件列表
const queryTable = async () => {
  const params = queryParams.value;
  const data = await querySparePartsWarehousing(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    facCode: "",
    inNum: "",
    inName: "",
    startTime: "",
    endTime: "",
    approvalStatus: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 审核进度弹窗
const handleProcess = (row: any) => {
  processVisible.value = true;
  sparePartsId.value = row.id;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
};
// 查看备件详情
const handleView = (row: any) => {
  drawerType.value = "view";
  sparePartsId.value = row.id;
  isMain.value = false;
  isView.value = true;
};
// 添加备件入库
const addSpareParts = command => {
  drawerType.value = "add";
  addType.value = command;
  isMain.value = false;
  isView.value = false;
};
// 编辑备件入库
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  sparePartsId.value = row.id;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
  isMain.value = false;
  isView.value = false;
};
// 审核备件入库
const handleCheck = (row: any) => {
  checkVisible.value = true;
  sparePartsId.value = row.id;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
};
// 转审备件入库
const handleToCheck = (row: any) => {
  toCheckVisible.value = true;
  sparePartsId.value = row.id;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
};
// 删除备件入库
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前备件入库单号“${row.inNum}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const params = {
        id: row.id
      };
      await deleteSparePartsWarehousing(params);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");
</style>
